package system;

import java.awt.image.BufferedImage;

import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class AnimatedSprite {

	private BufferedImage spritesheet;      // source spritesheet
	private int width;                      // width of each sprite
	private int height;                     // height of each sprite
	private int frameLength;				// length of each frame (ms)
	private boolean looping;                // should the animation loop?


	// Calculated
	private BufferedImage[] animation;      // array of each sprite on sheet
	private int frameIndex;                 // the frame the animation is on
	private int totalFrames;                // the total number of frames


	// System
	private long lastUpdate;                // last time sprite was updated
	private long currentTime;               // the current time


	public AnimatedSprite(File source, int frameWidth, int frameHeight, boolean isLoop, int frameLength) throws IOException {
		this.width = frameWidth;
		this.height = frameHeight;
		this.looping = isLoop;
		this.frameLength = frameLength;

		spritesheet = ImageIO.read(source);
		int fullWidth = spritesheet.getWidth();
		int fullHeight = spritesheet.getHeight();

		int columns = (int) fullWidth / width;
		int rows = (int) fullHeight / height;
		totalFrames = columns * rows;
		frameIndex = 0;
		animation = new BufferedImage[totalFrames];

		for(int i=0; i<rows; i++){
			for(int j=0; j<columns; j++){
				this.animation[i*columns + j] = this.spritesheet.getSubimage(width*j, height*i, width, height);
			}
		}

		currentTime = System.currentTimeMillis();
		lastUpdate = currentTime;
	}

	public BufferedImage getImage(){               // return the image of the current frame
		if(frameIndex > totalFrames){
			System.out.println("frameIndex error");
			return animation[0];
		}
		else{
			return animation[frameIndex];
		}
	}

	public void update(){
		if (frameLength > 0){
			currentTime = System.currentTimeMillis();
			if(currentTime - lastUpdate > frameLength) {
				lastUpdate = currentTime;
				frameIndex++;
				if(frameIndex>totalFrames-1 && looping) {
					frameIndex = 0;
				}
				else if(frameIndex > totalFrames-1 && !looping) {
					frameIndex = totalFrames-1;
				}
				else {
				}

			}
		}
	}

	// Getters
	public int getTotalFrames(){
		return totalFrames;
	}


	public int getWidth(){
		return width;
	}

	public int getHeight(){
		return height;
	}
	
	public int getFrameIndex(){
		return frameIndex;
	}

	// Setters
	public void setFrameIndex(int index) {
		frameIndex = index;
	}



}
